package com.ui.zhong.webview.mainproc

import android.util.Log
import com.google.gson.Gson
import com.ui.zhong.webview.ACallback
import com.ui.zhong.webview.AWebViewProcToMain
import com.ui.zhong.webview.command.Command
import java.util.ServiceLoader

class MainProcCommandManager : AWebViewProcToMain.Stub() {
    private val TAG = "MainProcCommandManager"
    var mCommands: HashMap<String, Command> = HashMap()

    init {
        val serviceLoader = ServiceLoader.load(Command::class.java)
        serviceLoader.forEach {
            if (!mCommands.containsKey(it.name())) {
                mCommands[it.name()] = it
            }
        }
    }

    companion object {
        private var sInstance: MainProcCommandManager? = null
        fun getInstance(): MainProcCommandManager {
            if (sInstance == null) {
                synchronized(MainProcCommandManager::class.java) {
                    sInstance = MainProcCommandManager()
                }
            }
            return sInstance!!
        }
    }

    override fun handleWebViewCmd(
        cmdName: String?, jsonParams:
        String?, callback: ACallback?
    ) {
        Log.i(TAG, "handleWebViewCmd: ${mCommands[cmdName]}")
        val paramMap = Gson().fromJson(jsonParams, Map::class.java) as Map<*, *>
        getInstance().executeCommand(cmdName, paramMap, callback)

    }

    private fun executeCommand(
        cmdName: String?,
        params: Map<*, *>,
        callback: ACallback?
    ) {
        mCommands[cmdName]?.execute(params, callback)
            ?: Log.e(TAG, "executeCommand: no command execute")
    }
}